#coding=utf-8
#LightCam VCS VIEW
#init by hfh 20160219

import multiprocessing,subprocess,sys
import socket,os,time,re,traceback,json,binascii
import lc_libs,pymongo


def genjson(filename,data):
	jdata={}
	jdata['rows']=data
	file=open(lchome+"/pyweb/static/json/vcs/"+filename+".json",'w')
	file.write(json.dumps(jdata))
	file.close()

#通过席位登录IP判断会员接入链路所在机房
def gen_jifang(ipaddr):
	
	result={}
	jifang = ''
	devicename=''
	deviceport=''
	portdesc=''
	
	iprec=r"((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)"
	if re.search(iprec,ipaddr):
		ips=ipaddr.split('.')
		
		#先判断是否为三所或托管机房地址
		if int(ips[0]) != 10:
			jifang = ''
		elif int(ips[1]) >= 0 and int(ips[1]) <= 15:
			jifang ="大商所"
		elif int(ips[1]) >= 16 and int(ips[1]) <= 31:
			jifang ="郑商所"
		elif int(ips[1]) >= 32 and int(ips[1]) <= 79:
			jifang = "上期所"
		elif int(ips[1]) >= 80 and int(ips[1]) <= 95:
			jifang = "大商所"
		elif int(ips[1]) >= 96 and int(ips[1]) <= 111:
			jifang = "郑商所"
		elif int(ips[1]) == 116:
			if int(ips[2]) >= 129 and int(ips[2]) <= 131:
				jifang = "深证通"
			elif int(ips[2]) == 132:
				jifang = "大连飞创"
			elif int(ips[2]) == 133:
				jifang = "上证通"
			elif int(ips[2]) >= 134 and int(ips[2]) <= 137:
				jifang = "数讯"
			elif int(ips[2]) == 138:
				jifang = "北京飞创"
			elif int(ips[2]) >= 140 and int(ips[2]) <= 143:
				jifang = "移动金桥"
			elif int(ips[2]) >= 144 and int(ips[2]) <= 147:
				jifang = "数讯"
			elif int(ips[2]) >= 160 and int(ips[2]) <= 167:
				jifang = "移动金桥"
			else:
				jifang = ''
		elif int(ips[1]) == 117:
			if int(ips[2]) == 133:
				jifang = "上证通"
			elif int(ips[2]) >= 134 and int(ips[2]) <= 137:
				jifang = "数讯"
			elif int(ips[2]) >= 140 and int(ips[2]) <= 143:
				jifang = "移动金桥"
			elif int(ips[2]) >= 144 and int(ips[2]) <= 147:
				jifang = "数讯"
			else:
				jifang = ''
		elif int(ips[1]) == 118:
			jifang = "上期技术"
		elif int(ips[1]) >= 128 and int(ips[1]) <= 143:
			jifang = "上期所"
		elif int(ips[1]) >= 160 and int(ips[1]) <= 175:
			jifang = "大商所"
		elif int(ips[1]) >= 176 and int(ips[1]) <= 191:
			jifang = "郑商所"
		elif int(ips[1]) == 210:
			if int(ips[2]) >= 0 and int(ips[2]) <= 7:
				jifang = "上期技术"
			elif int(ips[2]) == 8:
				jifang = "北京飞创"
			elif int(ips[2]) == 12:
				jifang = "大连飞创"
			else:
				jifang = ''
		elif int(ips[1]) == 213:
			if int(ips[2]) >= 0 and int(ips[2]) <= 7:
				jifang = "上期技术"
			elif int(ips[2]) == 8:
				jifang = "上证通"
			else:
				jifang = ''
		elif int(ips[1]) >= 240 and int(ips[1]) <= 255:
			jifang = "保证金"
		else:
			jifang = ''
			
		#对非三所和托管机房地址进行判断
		if jifang=='':
			if re.match("^10.113|^10.114|^10.115|^10.116|^10.117",ipaddr):
				jifang="外高桥直连"
			elif re.match("^10.209|^10.211|^10.212|^10.213|^10.214",ipaddr):
				jifang="张江直连"
			else:
				jifang="未知"
		
		#查找localiplist表确认接入路由器和接口信息
		tmp_ip=ipaddr.split('.')
		ipkey="%s.%s.%s" % (tmp_ip[0],tmp_ip[1],tmp_ip[2])
		if ipkey in localiplist.keys():
			devicename=localiplist[ipkey][0]
			deviceport=localiplist[ipkey][1]
			portdesc=localiplist[ipkey][2]
	else:
		jifang='未知'
	
	result={
		'jifang':jifang,
		'devicename':devicename,
		'deviceport':deviceport,
		'portdesc':portdesc
		}
	
	return result
	

if __name__ == "__main__":
	
	lchome=lc_libs.lc_getlchome()
	scname=sys.argv[0].split('.')[0]
	logfilename=lchome+'/log/'+scname+'.log'
	confname=lchome+'/conf/'+scname+'.conf'
	
	today=time.strftime('%Y%m%d',time.localtime())
	os.system("mv %s %s.%s" % (logfilename,logfilename,today))
	
	logfile=file(logfilename,'a')
	logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
	logfile.write(logdate+" Started.\n")
	logfile.flush()


	#初始化数据库
	
	db=lc_libs.lc_mongodb_operater('127.0.0.1',27017)

	db.connect()
	Conn=db.getConn()
	if Conn==None:
		print "Can not Connect to the MondbDB"
		exit(0)
	
	dbname='lc_vcs'
	psisdb=db.useDatabase(dbname)
	
	wan_crc=0
	memberlist={}
	localiplist={}
	
	while True:
		try:
			
			cmds='''
				cd /monitor/LightCam/scripts/;
				LightCamPy lc_batch.py "vcsbfrt1|vcsbfrt2" getsp /monitor/LightCam/temp/banklink.json banklink.json /monitor/LightCam/temp/;
				LightCamPy lc_batch.py "vcsmfrt1|vcsmfrt2" getsp /monitor/LightCam/temp/memberlink.json memberlink.json /monitor/LightCam/temp/;
				LightCamPy lc_batch.py "vcsbfrt1|vcsbfrt2|vcsmfrt1|vcsmfrt2" getsp /monitor/LightCam/temp/portstatus.json portstatus.json /monitor/LightCam/temp/;
				LightCamPy lc_batch.py "vcsarb|vcsbfrt1|vcsbfrt2|vcscomp1|vcscomp2|vcsdb1|vcsdb2|vcsmfrt1|vcsmfrt2|vcsses1|vcsses2|vcsssvr1|vcsssvr2|vcssync1|vcsusvr1|vcsusvr2" getsp /monitor/LightCam/temp/processstatus.json processstatus.json /monitor/LightCam/temp/
			'''
			
			#cmds="id"
			os.system(cmds)
			
			
			#会员链路wan表
			#对端名称	会员号	会员类型	运营商	链路类型	带宽	数据中心	接入设备	互联地址本端	互连地址对端	局域网段	总头	接口	专线编号	申请单位
			#上期所北京灾备	(null)	三所	电信	ATM	10M	外高桥	W_JR_JR_R01	10.128.201.10	10.128.201.9	(null)	ATM1/0/0	ATM1/0/0.100		对端
			#中信建投	0115	交易结算会员	电信	SDH	2M	外高桥	W_JR_JR_R04	10.112.0.42	10.112.0.41	10.113.10.0/24	Serial1/1/0	Serial1/1/0.1/2/3/3:0	北京上海30N3999NP	交易所

			wanfile=open(lchome+'/conf/lc_wan.conf',"rb").read()
			filecrc=binascii.crc32(wanfile)
			if wan_crc != filecrc:
				wan_crc=filecrc
				memberlist={}
				localiplist={}
				for lines in wanfile.split('\n'):
					if lines=='':
						continue
					if lines[0]=='#':
						continue
					line=lines.split('\t')
					if len(line)<4:
						continue
					
					memberlist[line[1]]=line[0]
					
					#局域网段	接入路由器	接入总头	接入端	会员名称	会员号
					#10.113.109.0/24	W_JR_JR_R03	Serial1/1/0	Serial2/0/0.1/1/3/3:0
					iprec=r"((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)"
					if re.search(iprec,line[10]):
						ipkey=line[10].replace('.0/24','')
						localiplist[ipkey]=[line[7],line[11],line[12],line[0],line[1]]
					#print localiplist.keys()
					
			
			
			#银行连接情况统计
			thisfile=open("/monitor/LightCam/temp/vcsbfrt1_banklink.json","rb")
			datastr1=thisfile.read()
			thisfile.close()
			
			thisfile=open("/monitor/LightCam/temp/vcsbfrt2_banklink.json","rb")
			datastr2=thisfile.read()
			thisfile.close()
			
			jsondata1=json.loads(datastr1)
			jsondata2=json.loads(datastr2)
			
			jsondata=jsondata1+jsondata2
			
			for item in jsondata:
				ipaddr=item['ipaddr']
				genres=gen_jifang(ipaddr)
				jifang=genres['jifang']
				devicename=genres['devicename']
				deviceport=genres['deviceport']
				portdesc=genres['portdesc']
				item['jifang']=jifang
				item['devicename']=devicename
				item['deviceport']=deviceport
				item['portdesc']=portdesc
				
				if '10.125.41.1' in ipaddr:
					item['bankname']='交通银行总行'
				elif '10.125.42.2' in ipaddr:
					item['bankname']='民生银行'
				elif '10.125.43.22' in ipaddr:
					item['bankname']='兴业银行'
				elif '10.125.45.179' in ipaddr:
					item['bankname']='招商银行'
				elif '10.125.46.2' in ipaddr:
					item['bankname']='中信银行'
				elif '10.125.39.1' in ipaddr:
					item['bankname']='光大银行'
				elif '10.125.44.10' in ipaddr:
					item['bankname']='浦发银行'
				elif '10.125.38.1' in ipaddr:
					item['bankname']='汇丰银行'
				elif '10.125.49.10' in ipaddr:
					item['bankname']='平安银行'
				else:
					item['bankname']='未知'

			#print jsondata
			
			genjson('banklink',jsondata)
			
			
			
			
			#会员连接情况统计
			thisfile=open("/monitor/LightCam/temp/vcsmfrt1_memberlink.json","rb")
			datastr1=thisfile.read()
			thisfile.close()
			
			thisfile=open("/monitor/LightCam/temp/vcsmfrt2_memberlink.json","rb")
			datastr2=thisfile.read()
			thisfile.close()
			
			jsondata1=json.loads(datastr1)
			jsondata2=json.loads(datastr2)
			
			jsondata=jsondata1+jsondata2
			
			for item in jsondata:
				ipaddr=item['ipaddr']
				genres=gen_jifang(ipaddr)
				jifang=genres['jifang']
				devicename=genres['devicename']
				deviceport=genres['deviceport']
				portdesc=genres['portdesc']
				item['jifang']=jifang
				item['devicename']=devicename
				item['deviceport']=deviceport
				item['portdesc']=portdesc
				
				ipaddrs=ipaddr.split('.')
				ipkey="%s.%s.%s" % (ipaddrs[0],ipaddrs[1],ipaddrs[2])
				if ipkey in localiplist.keys():
					item['membername']=localiplist[ipkey][3]
					item['memberid']=localiplist[ipkey][4]
				else:
					item['membername']=''
					item['memberid']=''

			#print jsondata
			
			genjson('memberlink',jsondata)

			#端口状态统计
			thisfile=open("/monitor/LightCam/temp/vcsbfrt1_portstatus.json","rb")
			datastr1=thisfile.read()
			thisfile.close()
			
			thisfile=open("/monitor/LightCam/temp/vcsbfrt2_portstatus.json","rb")
			datastr2=thisfile.read()
			thisfile.close()
			
			thisfile=open("/monitor/LightCam/temp/vcsmfrt1_portstatus.json","rb")
			datastr3=thisfile.read()
			thisfile.close()
			
			thisfile=open("/monitor/LightCam/temp/vcsmfrt2_portstatus.json","rb")
			datastr4=thisfile.read()
			thisfile.close()
			
			jsondata1=json.loads(datastr1)
			jsondata2=json.loads(datastr2)
			jsondata3=json.loads(datastr3)
			jsondata4=json.loads(datastr4)
			
			jsondata=jsondata1+jsondata2+jsondata3+jsondata4

			#print jsondata

			connu=0
			for i in jsondata:
				if 'vcsmfrt' in i['hostname']:
					connu+=int(i['estab_con'])
			print connu
			#schedule='0-6,00:30-00:31'
			#time_state = lc_libs.lc_schedule(schedule)
			#if time_state and connu < 100:
			#	Severity="3"
			#	Type="1"
			#	Summary="VCS MEMBER CONN less then 100"
			#	strs=lc_libs.lc_gen_alert(agent_hostname,Node,AlertGroup,AlertKey,Severity,Type,Summary)
			#	print strs
			#	db.update_eventsdb(events_table,agent_hostname,Node,AlertGroup,AlertKey,Severity,Type,Summary)
			#else:
			#	Severity="1"
			#	Type="2"
			#	Summary="VCS MEMBER CONN more then 100"
			#	strs=lc_libs.lc_gen_alert(agent_hostname,Node,AlertGroup,AlertKey,Severity,Type,Summary)
			#	print strs
			#	db.update_eventsdb(events_table,agent_hostname,Node,AlertGroup,AlertKey,Severity,Type,Summary)

			if connu < 100:
				logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
				logfile.write(logdate+" "+strs+"\n")
				logfile.flush()
			
			genjson('portstatus',jsondata)



			#进程状态统计
			vcslist=[
				'vcsarb',
				'vcsbfrt1',
				'vcsbfrt2',
				'vcscomp1',
				'vcscomp2',
				'vcsmfrt1',
				'vcsmfrt2',
				'vcsses1',
				'vcsses2',
				'vcsssvr1',
				'vcsssvr2',
				'vcssync1',
				'vcsusvr1',
				'vcsusvr2'
				]
			
			jsondata=[]
			
			for hostname in vcslist:
				thisfile=open("/monitor/LightCam/temp/"+hostname+"_processstatus.json","rb")
				datastr=thisfile.read()
				thisfile.close()
				jsondata+=json.loads(datastr)
				
			#print jsondata
			genjson('processstatus',jsondata)

			time.sleep(60)

		except Exception:
			excinfo=traceback.format_exc()
			logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
			logfile.write(logdate+" \n"+excinfo+"\n")
			logfile.flush()
			time.sleep(60)
			continue

